package com.hbnu.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.constant.RoleConstant;
import com.hbnu.system.constant.StatusCheckConstant;
import com.hbnu.system.core.base.CommonPage;
import com.hbnu.system.mapper.TPlatformMapper;
import com.hbnu.system.model.context.BaseContext;
import com.hbnu.system.model.dto.CheckBackDTO;
import com.hbnu.system.model.dto.TPlatformDTO;
import com.hbnu.system.model.entity.Audit;
import com.hbnu.system.model.entity.TPlatform;
import com.hbnu.system.model.entity.TPlatformfile;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.model.query.TPlatformPageQuery;
import com.hbnu.system.service.AuditService;
import com.hbnu.system.service.IUserService;
import com.hbnu.system.service.TPlatformService;
import com.hbnu.system.service.TPlatformfileService;
import com.hbnu.system.utils.CheckAuditHelper;
import com.hbnu.system.utils.CheckRoleUtil;
import com.hbnu.system.utils.UserInfoUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 平台信息表(TPlatform)表服务实现类
 *
 * @author makejava
 * @since 2025-07-16 14:25:42
 */
@Service
public class TPlatformServiceImpl extends ServiceImpl<TPlatformMapper, TPlatform> implements TPlatformService {
    @Autowired
    private TPlatformService iTPlatformService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private AuditService auditService;
    @Autowired
    private TPlatformfileService tPlatformfileService;
    @Autowired
    private TPlatformMapper tPlatformMapper;

    @Autowired
    private CheckRoleUtil checkRoleUtil;

    @Autowired
    private UserInfoUtils userInfoUtils;

    @Autowired
    private CheckAuditHelper checkAuditHelper ;

    @Override
    public boolean checkTPlatformname(String name){
        TPlatform one = super.getOne(Wrappers.lambdaQuery(TPlatform.class)
                .eq(TPlatform::getPlatformName, name));
        if(Objects.nonNull(one)){
            throw new BaseException("该科研平台名称已存在!");
        }
        return true;
    }

    /**
     * 新增科研平台
     * @param tPlatformdto
     * @return
     */
    @Override
    public boolean addnewtPlatform(TPlatformDTO tPlatformdto) {
//        System.out.println(tPlatform);

        checkRoleUtil.checkPermissionTplatform(tPlatformdto.getStatus());
        checkaddTPlatform(tPlatformdto);

        List<String> tPlatformCategory_id= tPlatformdto.getPlatformCategory();
        if(tPlatformCategory_id==null){
            throw new BaseException("请输入科研平台类别id");
        }

        User user = iUserService.getUserByAccount(tPlatformdto.getContactPersonId());
//        tPlatformdto.setContactPerson(user.getName());
//        if (user==null) {
//            throw new BaseException("输入负责人工号信息错误!");
//        }

        String categoryIdsStr = tPlatformCategory_id.stream()
                .collect(Collectors.joining(","));

        TPlatform tPlatform = new TPlatform();
        BeanUtils.copyProperties(tPlatformdto, tPlatform);
        tPlatform.setPlatformCategory(categoryIdsStr);

        TPlatform one = super.getOne(Wrappers.lambdaQuery(TPlatform.class).eq(TPlatform::getPlatformName, tPlatform.getPlatformName()));
        if (Objects.nonNull(one)&& !(one.getId().equals(tPlatform.getId()))) {
            throw new BaseException("该科研平台名已被使用");
        }

        tPlatform.setStatus("草稿");

        tPlatform.setEnteredtime(LocalDateTime.now());
        return baseMapper.insert(tPlatform) == 1;
    }

    /**
     * 修改科研平台
     * @param tPlatformdto
     * @return
     */
    @Override
    public boolean updatetPlatform(TPlatformDTO tPlatformdto) {
        checkRoleUtil.checkPermissionTplatform(tPlatformdto.getStatus());

        checkupdataTPlatform(tPlatformdto);

        List<String> tPlatformCategory_id= tPlatformdto.getPlatformCategory();
        if(tPlatformCategory_id==null){
            throw new BaseException("请输入科研平台类别id");
        }

        String categoryIdsStr = tPlatformCategory_id.stream()
                .collect(Collectors.joining(","));

        TPlatform tPlatform = new TPlatform();
        BeanUtils.copyProperties(tPlatformdto, tPlatform);
        tPlatform.setPlatformCategory(categoryIdsStr);

        //判断科研平台名是否修改重复
        TPlatform one = super.getOne(Wrappers.lambdaQuery(TPlatform.class)
                .eq(TPlatform::getPlatformName, tPlatform.getPlatformName())
                .ne(TPlatform::getId, tPlatform.getId()));
        if (Objects.nonNull(one)) {
            throw new BaseException("该科研平台名已被使用");
        }

        return baseMapper.updateById(tPlatform) == 1;
    }

    /**
     * 删除作品
     * @param tPlatformID 科研平台id
     * @return
     * @throws IOException
     */
    @Override
    @Transactional
    public boolean deletetPlatform(String tPlatformID) throws IOException {
        System.out.println("dsdsds");
        System.out.println(tPlatformID);
        // 校验普通用户权限不能修改当前状态信息
        TPlatform tPlatform = tPlatformMapper.selectById(tPlatformID);
        System.out.println(tPlatform);
        checkRoleUtil.checkPermissionTplatform(tPlatform.getStatus());

        // 删除科研平台关联的文件信息根据科研平台id
        tPlatformfileService.remove(Wrappers.lambdaQuery(TPlatformfile.class)
                .eq(TPlatformfile::getTplatformid, tPlatformID));

        // 删除文件信息
        List<TPlatformfile> tPlatformFiles = tPlatformfileService.list(Wrappers.lambdaQuery(TPlatformfile.class)
                .eq(TPlatformfile::getTplatformid, tPlatformID));
        List<String> fileIds = tPlatformFiles.stream()
                .map(TPlatformfile::getFileid)
                .collect(Collectors.toList());
        for (String fileId : fileIds) {
            tPlatformfileService.deletTPlatformfile(fileId);
        }
        // 删除审核记录根据科研平台ID
        auditService.remove(Wrappers.lambdaQuery(Audit.class)
                .eq(Audit::getSynthesisID, tPlatformID));

        // 最后删除科研平台本身
        return baseMapper.deleteById(tPlatformID) == 1;
    }




    @Override
    public TPlatformDTO getTPlatformDTO(String id) {
        TPlatform tPlatform = super.getOne(Wrappers.lambdaQuery(TPlatform.class)
                .eq(TPlatform::getId, id));

        String categoryIdsStr = tPlatform.getPlatformCategory();
        List<String> tPlatformCategory = new ArrayList<>(Arrays.asList(categoryIdsStr.split(",")));
        TPlatformDTO tPlatformDTO = new TPlatformDTO();
        BeanUtils.copyProperties(tPlatform, tPlatformDTO);
        tPlatformDTO.setPlatformCategory(tPlatformCategory);

        if (Objects.isNull(tPlatform)) {
            throw new BaseException("科研平台编号异常!未查找到该科研平台");
        }
        return tPlatformDTO;

    }

    @Override
    public TPlatform getTPlatform(String id){
        TPlatform tPlatform = super.getOne(Wrappers.lambdaQuery(TPlatform.class)
                .eq(TPlatform::getId, id));

//        String categoryIdsStr = tPlatform.getPlatformCategory_id();
//        List<String> tPlatformCategory_id = new ArrayList<>(Arrays.asList(categoryIdsStr.split(",")));
//        TPlatformDTO tPlatformDTO = new TPlatformDTO();
//        BeanUtils.copyProperties(tPlatform, tPlatformDTO);

        if (Objects.isNull(tPlatform)) {
            throw new BaseException("科研平台编号异常!未查找到该科研平台");
        }
        return tPlatform;
    }


    /**
     * 科研平台审核相关方法优化（统一使用 CheckAuditHelper）
     */
    @Override
    public Boolean collegeCheckPass(String token, String id) {
        TPlatform platform = iTPlatformService.getTPlatform(id);
        if (platform == null) throw new BaseException("该科研平台编号有误!");

        String roleName = userInfoUtils.getCurrentUserInfo().getRoleName();
        // 目标状态：如果是院级审核人则进入待校级审核，否则审核通过
        String targetStatus = StatusCheckConstant.COLLEGE_CHECK_PEOPLE.equals(roleName)
                ? StatusCheckConstant.WAIT_SCHOOL_CHECK
                : StatusCheckConstant.CHECK_PASS;

        return checkAuditHelper.doPassAudit(
                platform,
                StatusCheckConstant.WAIT_COLLEGE_CHECK,
                targetStatus,
                roleName,
                "科研平台",
                platform::getId,
                platform::getStatus,
                platform::setStatus,
                this::updatePlatformByEntity
        );
    }

    @Override
    public Boolean collegeCheckBack(String token, CheckBackDTO checkBackDTO) {
        TPlatform platform = iTPlatformService.getTPlatform(checkBackDTO.getID());
        if (platform == null) throw new BaseException("该科研平台编号有误!");

        String roleName = userInfoUtils.getCurrentUserInfo().getRoleName();
        // 退回状态：由审核人角色决定退回类型
        String backStatus = StatusCheckConstant.COLLEGE_CHECK_PEOPLE.equals(roleName)
                ? StatusCheckConstant.COLLEGE_CHECK_BACK
                : StatusCheckConstant.SCHOOL_CHECK_BACK;

        return checkAuditHelper.doBackAudit(
                platform,
                StatusCheckConstant.WAIT_COLLEGE_CHECK,
                backStatus,
                checkBackDTO.getReason(),
                "科研平台",
                platform::getId,
                platform::getStatus,
                platform::setStatus,
                platform::setReason,
                this::updatePlatformByEntity
        );
    }

    @Override
    public Boolean schoolCheckPass(String token, String id) {
        TPlatform platform = iTPlatformService.getTPlatform(id);
        if (platform == null) throw new BaseException("该科研平台编号有误!");

        String currentStatus = platform.getStatus();
        if (!StatusCheckConstant.WAIT_SCHOOL_CHECK.equals(currentStatus)
                && !StatusCheckConstant.WAIT_COLLEGE_CHECK.equals(currentStatus)) {
            throw new BaseException("该科研平台状态不处于该环节!");
        }

        String roleName = userInfoUtils.getCurrentUserInfo().getRoleName();

        return checkAuditHelper.doPassAudit(
                platform,
                currentStatus,
                StatusCheckConstant.CHECK_PASS,
                roleName,
                "科研平台",
                platform::getId,
                platform::getStatus,
                platform::setStatus,
                this::updatePlatformByEntity
        );
    }

    @Override
    public Boolean schoolCheckBack(String token, CheckBackDTO checkBackDTO) {
        TPlatform platform = iTPlatformService.getTPlatform(checkBackDTO.getID());
        if (platform == null) throw new BaseException("该科研平台编号有误!");

        String currentStatus = platform.getStatus();
        if (!StatusCheckConstant.WAIT_SCHOOL_CHECK.equals(currentStatus)
                && !StatusCheckConstant.WAIT_COLLEGE_CHECK.equals(currentStatus)) {
            throw new BaseException("该科研平台状态不处于该环节!");
        }

        String roleName = userInfoUtils.getCurrentUserInfo().getRoleName();

        return checkAuditHelper.doBackAudit(
                platform,
                currentStatus,
                StatusCheckConstant.SCHOOL_CHECK_BACK,
                checkBackDTO.getReason(),
                "科研平台",
                platform::getId,
                platform::getStatus,
                platform::setStatus,
                platform::setReason,
                this::updatePlatformByEntity
        );
    }


    private Boolean updatePlatformByEntity(TPlatform platform) {
        return baseMapper.updateById(platform) == 1;
    }

    /**
     * 科研平台提交
     * @param id
     * @return
     */
    @Override
    public Boolean ReCommitTPlatform(String id) {
        TPlatform tPlatform = super.getOne(Wrappers.lambdaQuery(TPlatform.class)
                .eq(TPlatform::getId,id));
        //检查字段是否填写
        checkCommitField(tPlatform);
        if(!tPlatform.getStatus().equals("草稿") && !tPlatform.getStatus().equals("被院级退回") && !tPlatform.getStatus().equals("被校级退回")){
            throw new BaseException("该科研平台目前状态不可提交!");
        }
        tPlatform.setStatus(StatusCheckConstant.WAIT_COLLEGE_CHECK);
        tPlatform.setReason("");
        return baseMapper.updateById(tPlatform) == 1;
    }
    
    @Override
    public Boolean withdrawTPlatform(String token, String id) {
        TPlatform tPlatform = getById(id);
        if(tPlatform==null){
            throw new BaseException("该科研平台不存在!");
        }
        
        // 检查状态是否可以撤回
        String currentStatus = tPlatform.getStatus();
        if (!StatusCheckConstant.WAIT_COLLEGE_CHECK.equals(currentStatus)) {
            throw new BaseException("该科研平台状态不允许撤回!");
        }
        
        // 更新状态为草稿
        tPlatform.setStatus("草稿");
        tPlatform.setReason("用户主动撤回");
        
        // 添加审计记录
        String currentId = BaseContext.getCurrentId();
        User userByAccount = iUserService.getById(currentId);
        Audit audit = new Audit();
        audit.setSynthesisID(id);
        audit.setAuditOpinion("用户主动撤回");
        audit.setAuditerRole(userByAccount.getRole());
        audit.setAuditerName(userByAccount.getName());
        audit.setStatusChange(currentStatus + "->草稿");
        audit.setAuditerTime(LocalDateTime.now());
        auditService.addAudit(audit);
        
        return baseMapper.updateById(tPlatform) == 1;
    }

    /**
     * 科研平台分页查询
     * @param tPlatformPageQuery
     * @return
     */
    @Override
    public CommonPage<TPlatform> userGetRelateTPlatformDTO(TPlatformPageQuery tPlatformPageQuery) {
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        String role = user.getRole();


        // 创建MyBatis-Plus的Page对象
        Page<TPlatform> page = new Page<>(tPlatformPageQuery.getPageNum(), tPlatformPageQuery.getPageSize());
        IPage<TPlatform> tPlatformIPage = null;


        // 根据角色执行不同查询
        if (role.equals(RoleConstant.ROLE_ADMIN_SCHOOL)) {
            tPlatformIPage = tPlatformMapper.schoolGetRelateTPlatformQuery(page, tPlatformPageQuery, user);
        } else if (role.equals(RoleConstant.ROLE_ADMIN_COLLEGE)) {
            tPlatformIPage = tPlatformMapper.collegeGetRelateTPlatformQuery(page, tPlatformPageQuery, user);
        } else {
            tPlatformIPage = tPlatformMapper.userGetRelateTPlatformQuery(page, tPlatformPageQuery, user);
        }


        // 构造返回分页对象
        CommonPage<TPlatform> tPlatformCommonPage = CommonPage.restPage(tPlatformIPage);

        return tPlatformCommonPage;
    }

    /**
     * 导出
     * @param
     * @return 导出数据
     */
    @Override
    public CommonPage<TPlatform> export(TPlatformPageQuery tPlatformPageQuery) {
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        String role = user.getRole();

        Page<TPlatform> page = new Page<>(tPlatformPageQuery.getPageNum(), tPlatformPageQuery.getPageSize());
        IPage<TPlatform> tPlatformIPage;

        if (RoleConstant.ROLE_ADMIN_SCHOOL.equals(role)) {
            tPlatformIPage = tPlatformMapper.schoolExportRelateTPlatformQuery(page, tPlatformPageQuery, user);
        } else if (RoleConstant.ROLE_ADMIN_COLLEGE.equals(role)) {
            tPlatformIPage = tPlatformMapper.collegeExportRelateTPlatformQuery(page, tPlatformPageQuery, user);
        } else {
            tPlatformIPage = tPlatformMapper.userExportRelateTPlatformQuery(page, tPlatformPageQuery, user);
        }

        List<TPlatform> records = tPlatformIPage.getRecords();

        float figure = 0;

        CommonPage<TPlatform> tPlatformCommonPage = CommonPage.restPage(tPlatformIPage);
        tPlatformCommonPage.setFigure(figure);
        tPlatformCommonPage.setList(records);
        return tPlatformCommonPage;
    }



    /**
     * 检查提交字段是否填写
     * @param tPlatform
     */
    private void checkCommitField(TPlatform tPlatform) {
        if(Objects.isNull(tPlatform)){
            throw new BaseException("科研平台编号有误!");
        }
//        checkupdataTPlatform(tPlatform);
        if (StrUtil.isEmpty(tPlatform.getPlatformName()) || StrUtil.isBlank(tPlatform.getPlatformName())){
            throw new BaseException("请输入科研平台名!");
        }
        if (StrUtil.isEmpty(tPlatform.getLevel()) || StrUtil.isBlank(tPlatform.getLevel())){
            throw new BaseException("请输入科研平台级别!");
        }
        if (StrUtil.isEmpty(tPlatform.getPlatformCategory()) || StrUtil.isBlank(tPlatform.getPlatformCategory())){
            throw new BaseException("请输入科研平台类别!");
        }
        if(StrUtil.isEmpty(tPlatform.getEntered()) || StrUtil.isBlank(tPlatform.getEntered())){
            throw new BaseException("请输入录入人");
        }
        if (StrUtil.isEmpty(tPlatform.getApprovalUnit()) || StrUtil.isBlank(tPlatform.getApprovalUnit())){
            throw new BaseException("请输入批准单位!");
        }
        if (StrUtil.isEmpty(tPlatform.getContactPersonId()) || StrUtil.isBlank(tPlatform.getContactPersonId())){
            throw new BaseException("请输入负责人/联系人工号!");
        }
        if (StrUtil.isEmpty(tPlatform.getOperationStatus()) || StrUtil.isBlank(tPlatform.getOperationStatus())){
            throw new BaseException("请输入运营状态!");
        }
        if(StrUtil.isEmpty(tPlatform.getSupportCollege()) || StrUtil.isBlank(tPlatform.getSupportCollege())){
            throw new BaseException("请输入依托学院!");
        }
//        if(StrUtil.isEmpty(tPlatform.getContactPersonId()) || StrUtil.isBlank(tPlatform.getContactPersonId())){
//            throw new BaseException("请输入负责人/联系人工号!");
//        }
    }

    private void checkaddTPlatform(TPlatformDTO tPlatform) {
        if (StrUtil.isEmpty(tPlatform.getPlatformName()) || StrUtil.isBlank(tPlatform.getPlatformName())){
            throw new BaseException("请输入科研平台名!");
        }
        if (StrUtil.isEmpty(tPlatform.getLevel()) || StrUtil.isBlank(tPlatform.getLevel())){
            throw new BaseException("请输入科研平台级别!");
        }
        if (StrUtil.isEmpty(tPlatform.getPlatformCategoryName()) || StrUtil.isBlank(tPlatform.getPlatformCategoryName())){
            throw new BaseException("请输入科研平台类别!");
        }
        if(StrUtil.isEmpty(tPlatform.getEntered()) || StrUtil.isBlank(tPlatform.getEntered())){
            throw new BaseException("请输入录入人");
        }
        if (StrUtil.isEmpty(tPlatform.getApprovalUnit()) || StrUtil.isBlank(tPlatform.getApprovalUnit())){
            throw new BaseException("请输入批准单位!");
        }
        if (StrUtil.isEmpty(tPlatform.getContactPersonId()) || StrUtil.isBlank(tPlatform.getContactPersonId())){
            throw new BaseException("请输入负责人/联系人工号!");
        }
        if (StrUtil.isEmpty(tPlatform.getOperationStatus()) || StrUtil.isBlank(tPlatform.getOperationStatus())){
            throw new BaseException("请输入运营状态!");
        }
        if(StrUtil.isEmpty(tPlatform.getSupportCollege()) || StrUtil.isBlank(tPlatform.getSupportCollege())){
            throw new BaseException("请输入依托学院!");
        }
//        if(StrUtil.isEmpty(tPlatform.getContactPersonId()) || StrUtil.isBlank(tPlatform.getContactPersonId())){
//            throw new BaseException("请输入负责人/联系人工号!");
//        }

    }

    private void checkupdataTPlatform(TPlatformDTO tPlatform){
        if (StrUtil.isEmpty(tPlatform.getPlatformName()) || StrUtil.isBlank(tPlatform.getPlatformName())){
            throw new BaseException("请输入科研平台名!");
        }
        if (StrUtil.isEmpty(tPlatform.getLevel()) || StrUtil.isBlank(tPlatform.getLevel())){
            throw new BaseException("请输入科研平台级别!");
        }
        if (StrUtil.isEmpty(tPlatform.getPlatformCategoryName()) || StrUtil.isBlank(tPlatform.getPlatformCategoryName())){
            throw new BaseException("请输入科研平台类别!");
        }
        if (StrUtil.isEmpty(tPlatform.getApprovalUnit()) || StrUtil.isBlank(tPlatform.getApprovalUnit())){
            throw new BaseException("请输入批准单位!");
        }
        if (StrUtil.isEmpty(tPlatform.getContactPersonId()) || StrUtil.isBlank(tPlatform.getContactPersonId())){
            throw new BaseException("请输入负责人/联系人工号!");
        }
        if (StrUtil.isEmpty(tPlatform.getOperationStatus()) || StrUtil.isBlank(tPlatform.getOperationStatus())){
            throw new BaseException("请输入运营状态!");
        }
        if(StrUtil.isEmpty(tPlatform.getSupportCollege()) || StrUtil.isBlank(tPlatform.getSupportCollege())){
            throw new BaseException("请输入依托学院!");
        }
//        if(StrUtil.isEmpty(tPlatform.getContactPersonId()) || StrUtil.isBlank(tPlatform.getContactPersonId())){
//            throw new BaseException("请输入负责人/联系人工号!");
//        }
    }


    
}

